package com.xp.pgoj.ws;

import com.xp.pgoj.config.GetHttpSessionConfig;
import com.xp.pgoj.model.entity.User;
import com.xp.pgoj.service.CommentService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.xp.pgoj.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author <a href=""https://github.com/Fzs0>逢左使</a>
 * @create 2024/09/24 20:12
 * @Description:
 */
@ServerEndpoint(value = "/webSocket", configurator = GetHttpSessionConfig.class)
@Component
public class WebsocketServer {

    private static final Map<String, Session> ojOnlineUser = new ConcurrentHashMap<>();

    private HttpSession httpSession;

    @Resource
    private CommentService commentService;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        // 将httpSession进行保存
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        User user = (User) httpSession.getAttribute(USER_LOGIN_STATE);
        // 维护会话等
        ojOnlineUser.put(user.getId().toString(), session);
        session.getBasicRemote().sendText(user.getId().toString() + "登录了！！！");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        // 销毁会话等
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        // 收到客户端发送的消息

    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        // 发生错误时
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        User user = (User) httpSession.getAttribute(USER_LOGIN_STATE);
        // 维护会话等 todo 把当前登录用户id设置map的key
        Session session = ojOnlineUser.get(user.getId().toString());
        session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
        // 从会话管理器中获取会话，进行群发
    }

}
